import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  Upload,
  message,
  Space,
  Modal,
  Row,
  Col,
  Typography,
  Spin,
  Tabs,
  Divider,
  Alert,
  Progress
} from 'antd';
import {
  SaveOutlined,
  EyeOutlined,
  SendOutlined,
  PictureOutlined,
  FileOutlined,
  DeleteOutlined,
  CloudUploadOutlined,
  EditOutlined,
  FileTextOutlined,
  LoadingOutlined
} from '@ant-design/icons';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { getToken } from '../../utils';
import AiEditorComponent from '../../components/AiEditorComponent';
import ConversionProgress from '../../components/ConversionProgress/ConversionProgress';
import './Works.scss';

const { Title, Text, Paragraph } = Typography;
const { TabPane } = Tabs;
const { TextArea } = Input;

const Works = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const workId = searchParams.get('id');
  const isEdit = !!workId;

  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [publishing, setPublishing] = useState(false);
  const [content, setContent] = useState('');
  const [description, setDescription] = useState(''); // 作品描述
  const [coverImage, setCoverImage] = useState(null);
  const [attachments, setAttachments] = useState([]);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewContent, setPreviewContent] = useState('');
  const [activeTab, setActiveTab] = useState('editor');
  const [uploadedDocuments, setUploadedDocuments] = useState([]);
  const [conversionProgress, setConversionProgress] = useState({}); // PDF转换进度
  const [isConverting, setIsConverting] = useState(false); // 是否正在转换
  const [attachmentFiles, setAttachmentFiles] = useState([]); // 编辑模式下的附件文件
  const editorRef = React.useRef(null);

  // 处理编辑器内容变化
  const handleContentChange = (newContent) => {
    setContent(newContent);
  };

  // 加载作品数据（编辑模式）
  useEffect(() => {
    if (isEdit) {
      loadWork();
    }
  }, [workId]);

  const loadWork = async () => {
    try {
      setLoading(true);
      const response = await fetch(`http://211.86.197.10:9091/api/articles/${workId}`);
      const result = await response.json();

      if (result.success) {
        const work = result.data;
        form.setFieldsValue({
          title: work.title,
          description: work.description || ''
        });
        setContent(work.content_html || '');
        setDescription(work.description || '');
        setCoverImage(work.cover_image);
        
        // 加载附件数据
        if (work.attachments && work.attachments.length > 0) {
          const formattedAttachments = work.attachments.map(attachment => ({
            id: attachment.id,
            name: attachment.original_name,
            url: attachment.file_url,
            type: attachment.mime_type,
            size: attachment.file_size,
            fileType: attachment.file_type,
            pdfUrl: attachment.pdf_url,
            pdfStatus: attachment.pdf_status,
            hasPdf: !!attachment.pdf_url
          }));
          setAttachments(formattedAttachments);
          setAttachmentFiles(formattedAttachments);
        }
      } else {
        message.error('加载作品失败');
        navigate('/');
      }
    } catch (error) {
      console.error('加载作品错误:', error);
      message.error('加载作品失败');
      navigate('/');
    } finally {
      setLoading(false);
    }
  };

  // 保存草稿
  const handleSaveDraft = async () => {
    try {
      const values = await form.validateFields(['title']);
      if (!content.trim()) {
        message.warning('请输入作品内容');
        return;
      }

      setSaving(true);
      const workData = {
        title: values.title,
        description: values.description || description || '',
        content: { html: content },
        content_html: content,
        cover_image: coverImage,
        status: 'draft'
      };

      const url = isEdit ? `http://211.86.197.10:9091/api/articles/${workId}` : 'http://211.86.197.10:9091/api/articles';
      const method = isEdit ? 'PUT' : 'POST';

      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${getToken()}`
        },
        body: JSON.stringify(workData)
      });

      const result = await response.json();

      if (result.success) {
        const savedWorkId = result.data.id;
        
        if (!isEdit) {
          await saveTemporaryAttachments(savedWorkId);
          navigate(`/works?id=${savedWorkId}`);
        }
        
        message.success('草稿保存成功');
      } else {
        message.error(result.message || '保存失败');
      }
    } catch (error) {
      console.error('保存草稿错误:', error);
      message.error('保存失败');
    } finally {
      setSaving(false);
    }
  };

  // 发布作品
  const handlePublish = async () => {
    try {
      const values = await form.validateFields();
      if (!content.trim()) {
        message.warning('请输入作品内容');
        return;
      }

      setPublishing(true);
      const workData = {
        title: values.title,
        description: values.description || description || '',
        content: { html: content },
        content_html: content,
        cover_image: coverImage,
        status: 'published'
      };

      const url = isEdit ? `http://211.86.197.10:9091/api/articles/${workId}` : 'http://211.86.197.10:9091/api/articles';
      const method = isEdit ? 'PUT' : 'POST';

      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${getToken()}`
        },
        body: JSON.stringify(workData)
      });

      const result = await response.json();

      if (result.success) {
        const publishedWorkId = result.data.id;
        
        if (!isEdit) {
          await saveTemporaryAttachments(publishedWorkId);
        }
        
        message.success('作品发布成功');
        navigate('/articles');
      } else {
        message.error(result.message || '发布失败');
      }
    } catch (error) {
      console.error('发布作品错误:', error);
      message.error('发布失败');
    } finally {
      setPublishing(false);
    }
  };

  // 预览作品
  const handlePreview = () => {
    const values = form.getFieldsValue();
    const previewHtml = `
      <div style="max-width: 800px; margin: 0 auto; padding: 20px;">
        <h1 style="text-align: center; margin-bottom: 20px;">${values.title || '未命名作品'}</h1>
        ${coverImage ? `<img src="${coverImage}" style="width: 100%; max-width: 600px; margin: 20px auto; display: block;" alt="封面图片" />` : ''}
        <div style="line-height: 1.6; font-size: 16px;">
          ${content || '<p>暂无内容</p>'}
        </div>
      </div>
    `;
    setPreviewContent(previewHtml);
    setPreviewVisible(true);
  };

  // 上传封面图片
  const handleCoverUpload = ({ file, onSuccess, onError }) => {
    const formData = new FormData();
    formData.append('file', file);

    fetch('http://211.86.197.10:9091/api/upload/image', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${getToken()}`
      },
      body: formData
    })
    .then(response => response.json())
    .then(result => {
      if (result.success) {
        setCoverImage(`http://211.86.197.10:9091${result.data.url}`);
        onSuccess();
        message.success('封面上传成功');
      } else {
        onError();
        message.error('封面上传失败');
      }
    })
    .catch(error => {
      console.error('上传错误:', error);
      onError();
      message.error('封面上传失败');
    });
  };

  // 上传附件文件（编辑模式）
  const handleAttachmentUpload = async ({ file, onSuccess, onError }) => {
    try {
      console.log('开始上传附件:', file.name);
      
      const formData = new FormData();
      formData.append('file', file);
      
      // 如果是编辑模式，添加作品ID和立即保存标志
      if (isEdit && workId) {
        formData.append('article_id', workId);
        formData.append('immediate_save', 'true');
      }

      const uploadResponse = await fetch('http://211.86.197.10:9091/api/upload/document', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${getToken()}`
        },
        body: formData
      });

      if (!uploadResponse.ok) {
        throw new Error(`上传失败: ${uploadResponse.status}`);
      }

      const uploadResult = await uploadResponse.json();
      
      if (!uploadResult.success) {
        throw new Error(uploadResult.message || '文件上传失败');
      }

      let attachmentData = {
        id: uploadResult.data.id || Date.now(), // 使用服务器返回的ID（如果有）
        name: uploadResult.data.originalName,
        url: `http://211.86.197.10:9091${uploadResult.data.url}`,
        type: uploadResult.data.type,
        size: uploadResult.data.size,
        fileType: getFileTypeFromMime(uploadResult.data.type),
        isTemporary: !uploadResult.data.id, // 如果有ID说明已保存到数据库
        uploadData: {
          file_name: uploadResult.data.filename,
          original_name: uploadResult.data.originalName,
          file_type: getFileTypeFromMime(uploadResult.data.type),
          file_size: uploadResult.data.size,
          file_url: uploadResult.data.url,
          mime_type: uploadResult.data.type
        }
      };

      // 检查是否有PDF转换结果（优先使用新的状态信息）
      if (uploadResult.data.pdf_status && uploadResult.data.pdf_status !== 'unknown') {
        attachmentData.pdfStatus = uploadResult.data.pdf_status;
        attachmentData.hasPdf = true;
        if (uploadResult.data.pdf_url) {
          attachmentData.pdfUrl = `http://211.86.197.10:9091${uploadResult.data.pdf_url}`;
        }
        attachmentData.isPlaceholder = uploadResult.data.pdf_status === 'placeholder';
        
        if (uploadResult.data.pdf_status === 'completed') {
          message.success(`${file.name} 上传成功，PDF版本已生成`);
        } else if (uploadResult.data.pdf_status === 'placeholder') {
          message.warning(`${file.name} 上传成功，PDF占位符已生成`);
        } else if (uploadResult.data.pdf_status === 'failed') {
          message.warning(`${file.name} 上传成功，但PDF转换失败`);
        }
      } else if (uploadResult.data.pdfConversion && uploadResult.data.pdfConversion.success) {
        // 兼容旧的返回格式
        attachmentData.pdfUrl = `http://211.86.197.10:9091${uploadResult.data.pdfConversion.pdfUrl}`;
        attachmentData.pdfFileName = uploadResult.data.pdfConversion.pdfFileName;
        attachmentData.hasPdf = true;
        attachmentData.pdfStatus = uploadResult.data.pdfConversion.isPlaceholder ? 'placeholder' : 'completed';
        attachmentData.isPlaceholder = uploadResult.data.pdfConversion.isPlaceholder || false;
        message.success(`${file.name} 上传成功，PDF版本已生成`);
      } else if (uploadResult.data.type === 'application/pdf') {
        // PDF文件直接使用原文件作为PDF版本
        attachmentData.pdfUrl = attachmentData.url;
        attachmentData.hasPdf = true;
        attachmentData.pdfStatus = 'completed';
        attachmentData.isOriginalPdf = true;
        message.success(`PDF文档 ${file.name} 上传成功`);
      } else {
        // 对于Word/PPT文档，如果没有PDF转换结果，标记为处理中
        const isWordOrPpt = [
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          'application/msword',
          'application/vnd.openxmlformats-officedocument.presentationml.presentation',
          'application/vnd.ms-powerpoint'
        ].includes(uploadResult.data.type);
        
        if (isWordOrPpt) {
          attachmentData.pdfStatus = 'processing';
          message.success(`${file.name} 上传成功，PDF转换中...`);
        } else {
          message.success(`${file.name} 上传成功`);
        }
      }

      // 添加到附件列表
      setAttachmentFiles(prev => [...prev, attachmentData]);
      
      onSuccess();
      
    } catch (error) {
      console.error('上传附件错误:', error);
      onError();
      message.error(error.message || '附件上传失败');
    }
  };

  // 上传文档并转换为HTML和PDF
  const handleDocumentUpload = async ({ file, onSuccess, onError }) => {
    try {
      console.log('开始上传文档:', file.name);
      
      // 初始化进度条
      const fileId = Date.now() + Math.random();
      setConversionProgress(prev => ({
        ...prev,
        [fileId]: { 
          percent: 0, 
          status: 'uploading', 
          fileName: file.name,
          stage: '准备上传...'
        }
      }));
      setIsConverting(true);
      
      const formData = new FormData();
      formData.append('file', file);

      // 更新进度：开始上传
      setConversionProgress(prev => ({
        ...prev,
        [fileId]: { 
          ...prev[fileId], 
          percent: 20, 
          status: 'uploading',
          stage: '正在上传文件...'
        }
      }));

      const uploadResponse = await fetch('http://211.86.197.10:9091/api/upload/document', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${getToken()}`
        },
        body: formData
      });

      if (!uploadResponse.ok) {
        throw new Error(`上传失败: ${uploadResponse.status}`);
      }

      // 更新进度：上传完成，开始转换
      setConversionProgress(prev => ({
        ...prev,
        [fileId]: { 
          ...prev[fileId], 
          percent: 40, 
          status: 'converting',
          stage: '文件上传完成，开始转换...'
        }
      }));

      const uploadResult = await uploadResponse.json();
      
      if (!uploadResult.success) {
        throw new Error(uploadResult.message || '文件上传失败');
      }

      let documentProcessed = false;
      let attachmentData = {
        id: Date.now(),
        name: uploadResult.data.originalName,
        url: `http://211.86.197.10:9091${uploadResult.data.url}`,
        type: uploadResult.data.type,
        size: uploadResult.data.size,
        fileType: getFileTypeFromMime(uploadResult.data.type),
        isTemporary: true,
        uploadData: {
          file_name: uploadResult.data.filename,
          original_name: uploadResult.data.originalName,
          file_type: getFileTypeFromMime(uploadResult.data.type),
          file_size: uploadResult.data.size,
          file_url: uploadResult.data.url,
          mime_type: uploadResult.data.type
        }
      };

      // 检查文档类型
      const isWordOrPpt = [
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        'application/vnd.ms-powerpoint'
      ].includes(uploadResult.data.type);

      const isPdf = uploadResult.data.type === 'application/pdf';

      // 更新进度：检测文档类型，准备PDF转换
      setConversionProgress(prev => ({
        ...prev,
        [fileId]: { 
          ...prev[fileId], 
          percent: 60, 
          status: 'converting',
          stage: isWordOrPpt ? '正在转换为PDF...' : isPdf ? '处理PDF文档...' : '处理文档...'
        }
      }));

      // 处理PDF转换结果（Word和PPT需要转换为PDF）
      if (uploadResult.data.pdfConversion && uploadResult.data.pdfConversion.success) {
        attachmentData.pdfUrl = `http://211.86.197.10:9091${uploadResult.data.pdfConversion.pdfUrl}`;
        attachmentData.pdfFileName = uploadResult.data.pdfConversion.pdfFileName;
        attachmentData.hasPdf = true;
        attachmentData.pdfStatus = uploadResult.data.pdfConversion.isPlaceholder ? 'placeholder' : 'completed';
        attachmentData.isPlaceholder = uploadResult.data.pdfConversion.isPlaceholder || false;
        
        // 更新进度：PDF转换完成
        setConversionProgress(prev => ({
          ...prev,
          [fileId]: { 
            ...prev[fileId], 
            percent: 85, 
            status: 'pdf_completed',
            stage: attachmentData.isPlaceholder ? 'PDF占位符已生成' : 'PDF转换完成'
          }
        }));
        
        if (isWordOrPpt) {
          message.success(`${file.name} 已成功转换为PDF，可在作品详情页预览`);
          documentProcessed = true;
        }
      }

      // 对于PDF文档，直接作为附件保存
      if (isPdf) {
        attachmentData.pdfUrl = attachmentData.url;
        attachmentData.hasPdf = true;
        attachmentData.pdfStatus = 'completed';
        attachmentData.isOriginalPdf = true;
        
        message.success(`PDF文档 ${file.name} 上传成功，可直接预览`);
        documentProcessed = true;
      }

      // 处理HTML转换结果（非Word/PPT/PDF文档转换为HTML并添加到编辑器）
      if (uploadResult.data.conversion && uploadResult.data.conversion.success && !isWordOrPpt && !isPdf) {
        const convertedHtml = uploadResult.data.conversion.html;
        
        // 将转换后的HTML内容添加到编辑器中
        const currentContent = content || '';
        const newContent = currentContent + '\n\n' + convertedHtml;
        setContent(newContent);
        
        // 更新编辑器内容
        if (editorRef.current) {
          editorRef.current.setContent(newContent);
        }

        if (!documentProcessed) {
          message.success(`文档 "${file.name}" 已转换并添加到内容中`);
          documentProcessed = true;
        }
      }

      // 保存为附件（包含PDF信息）
      setAttachments(prev => [...prev, attachmentData]);
      
      // 如果是文档上传模式，也添加到附件文件列表
      if (activeTab === 'upload') {
        setAttachmentFiles(prev => [...prev, attachmentData]);
      }

      // 处理未成功转换的情况
      if (!documentProcessed) {
        if (isWordOrPpt) {
          message.warning(`${file.name} PDF转换失败，但文件已上传，可在附件中查看原文件`);
          // 即使转换失败，也标记为附件
          attachmentData.pdfStatus = 'failed';
        } else {
          message.warning(`文档 "${file.name}" 上传成功，但转换失败，已保存为附件`);
        }
      }

      // 更新进度：完成
      setConversionProgress(prev => ({
        ...prev,
        [fileId]: { 
          ...prev[fileId], 
          percent: 100, 
          status: 'completed',
          stage: '处理完成'
        }
      }));

      // 记录上传的文档
      setUploadedDocuments(prev => [...prev, {
        name: file.name,
        url: `http://211.86.197.10:9091${uploadResult.data.url}`,
        pdfUrl: attachmentData.pdfUrl,
        converted: !!(uploadResult.data.conversion && uploadResult.data.conversion.success),
        hasPdf: !!attachmentData.hasPdf,
        isWordOrPpt: isWordOrPpt,
        isPdf: isPdf,
        isOriginalPdf: attachmentData.isOriginalPdf || false,
        pdfStatus: attachmentData.pdfStatus || 'unknown'
      }]);
      
      // 延迟清除进度条
      setTimeout(() => {
        setConversionProgress(prev => {
          const newProgress = { ...prev };
          delete newProgress[fileId];
          return newProgress;
        });
        setIsConverting(Object.keys(conversionProgress).length > 1);
      }, 2000);
      
      onSuccess();
      
    } catch (error) {
      console.error('上传错误:', error);
      
      // 更新进度：失败
      const fileId = Object.keys(conversionProgress).find(id => 
        conversionProgress[id].fileName === file.name
      );
      if (fileId) {
        setConversionProgress(prev => ({
          ...prev,
          [fileId]: { 
            ...prev[fileId], 
            percent: 0, 
            status: 'error',
            stage: '处理失败'
          }
        }));
        
        // 延迟清除进度条
        setTimeout(() => {
          setConversionProgress(prev => {
            const newProgress = { ...prev };
            delete newProgress[fileId];
            return newProgress;
          });
          setIsConverting(Object.keys(conversionProgress).length > 1);
        }, 9090);
      }
      
      onError();
      message.error(error.message || '文档上传失败');
    }
  };

  // 根据MIME类型获取文件类型
  const getFileTypeFromMime = (mimeType) => {
    if (mimeType.includes('image')) return 'image';
    if (mimeType.includes('video')) return 'video';
    return 'document';
  };

  // 保存临时附件到数据库
  const saveTemporaryAttachments = async (workId) => {
    // 合并所有临时附件（包括编辑模式的附件文件）
    const allTemporaryAttachments = [
      ...attachments.filter(att => att.isTemporary && att.uploadData),
      ...attachmentFiles.filter(att => att.isTemporary && att.uploadData)
    ];
    
    // 去重（基于文件名）
    const uniqueAttachments = allTemporaryAttachments.reduce((acc, current) => {
      const existing = acc.find(item => item.uploadData.file_name === current.uploadData.file_name);
      if (!existing) {
        acc.push(current);
      }
      return acc;
    }, []);
    
    if (uniqueAttachments.length === 0) {
      return;
    }

    for (const attachment of uniqueAttachments) {
      try {
        const response = await fetch(`http://211.86.197.10:9091/api/articles/${workId}/attachments`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${getToken()}`
          },
          body: JSON.stringify(attachment.uploadData)
        });

        const result = await response.json();
        
        if (result.success) {
          const attachmentId = result.data.id;
          
          // 如果有PDF转换结果，保存PDF转换信息
          if (attachment.hasPdf && attachment.pdfUrl) {
            try {
              const pdfResponse = await fetch(`http://211.86.197.10:9091/api/pdf-conversions`, {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json',
                  'Authorization': `Bearer ${getToken()}`
                },
                body: JSON.stringify({
                  original_file_id: attachmentId,
                  pdf_url: attachment.pdfUrl.replace('http://211.86.197.10:9091', ''), // 只保存相对路径
                  pdf_path: attachment.pdfFileName || '',
                  conversion_status: attachment.pdfStatus || (attachment.isPlaceholder ? 'placeholder' : 'completed')
                })
              });
              
              const pdfResult = await pdfResponse.json();
              if (!pdfResult.success) {
                console.error('保存PDF转换信息失败:', pdfResult.message);
              }
            } catch (pdfError) {
              console.error('保存PDF转换信息失败:', pdfError);
            }
          }
          
          // 更新附件列表中的ID
          setAttachments(prev => prev.map(att => 
            att.id === attachment.id 
              ? { ...att, id: attachmentId, isTemporary: false }
              : att
          ));
          
          // 更新附件文件列表中的ID
          setAttachmentFiles(prev => prev.map(att => 
            att.id === attachment.id 
              ? { ...att, id: attachmentId, isTemporary: false }
              : att
          ));
        }
      } catch (error) {
        console.error('保存附件错误:', attachment.name, error);
      }
    }
  };

  // 删除附件
  const handleDeleteAttachment = async (attachmentId) => {
    try {
      setAttachments(prev => prev.filter(item => item.id !== attachmentId));
      message.success('附件删除成功');
    } catch (error) {
      console.error('删除附件错误:', error);
      message.error('删除附件失败');
    }
  };

  // 删除附件文件
  const handleDeleteAttachmentFile = async (attachmentId) => {
    try {
      setAttachmentFiles(prev => prev.filter(item => item.id !== attachmentId));
      message.success('附件删除成功');
    } catch (error) {
      console.error('删除附件错误:', error);
      message.error('删除附件失败');
    }
  };

  if (loading) {
    return (
      <div className="loading-container">
        <Spin size="large" />
        <div className="loading-text">加载中...</div>
      </div>
    );
  }

  return (
    <div className="works-container">
      <Card>
        <Title level={2} style={{ textAlign: 'center', marginBottom: 24 }}>
          {isEdit ? '编辑作品' : '创建作品'}
        </Title>

        <Form form={form} layout="vertical">
          <Form.Item
            name="title"
            label={<span style={{ fontSize: '16px', fontWeight: 600 }}>作品标题</span>}
            rules={[{ required: true, message: '请输入作品标题' }]}
          >
            <Input 
              placeholder="请输入作品标题" 
              size="large"
              style={{ fontSize: '18px', fontWeight: 500 }}
            />
          </Form.Item>

          <Form.Item
            name="description"
            label={<span style={{ fontSize: '16px', fontWeight: 600 }}>作品描述</span>}
            rules={[{ max: 500, message: '描述不能超过500字符' }]}
          >
            <TextArea
              placeholder="请输入作品描述，简要介绍作品内容、创作背景等（可选）"
              rows={4}
              showCount
              maxLength={500}
              value={description}
              onChange={(e) => setDescription(e.target.value)}
            />
          </Form.Item>

          <Tabs activeKey={activeTab} onChange={setActiveTab} className="works-tabs">
            <TabPane 
              tab={
                <span>
                  <EditOutlined />
                  富文本编辑
                </span>
              } 
              key="editor"
            >
              <Alert
                message="富文本编辑模式"
                description="使用富文本编辑器创建内容，支持文字格式化、插入图片、表格等功能。"
                type="info"
                showIcon
                style={{ marginBottom: 16 }}
              />
              
              <AiEditorComponent
                ref={editorRef}
                value={content}
                onChange={handleContentChange}
                placeholder="开始创作你的精彩内容..."
                height="500px"
              />

              {/* 编辑模式下的附件上传区域 */}
              <div style={{ marginTop: 24 }}>
                <Title level={5}>
                  <FileOutlined style={{ marginRight: 8 }} />
                  作品附件
                </Title>
                <Text type="secondary" style={{ display: 'block', marginBottom: 16 }}>
                  上传与作品相关的文档、图片等附件文件。Word、PPT文档会自动转换为PDF格式便于预览。
                </Text>
                
                <Upload.Dragger
                  customRequest={handleAttachmentUpload}
                  showUploadList={false}
                  accept=".pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.txt,.jpg,.jpeg,.png,.gif"
                  multiple
                  style={{ marginBottom: 16 }}
                >
                  <p className="ant-upload-drag-icon">
                    <FileOutlined style={{ fontSize: 32, color: '#1890ff' }} />
                  </p>
                  <p className="ant-upload-text">点击或拖拽文件到此区域上传附件</p>
                  <p className="ant-upload-hint">
                    支持 Word、PDF、PowerPoint、Excel、图片等格式
                  </p>
                </Upload.Dragger>

                {/* 附件文件列表 */}
                {attachmentFiles.length > 0 && (
                  <div className="attachment-files-list">
                    <Title level={5}>已上传附件 ({attachmentFiles.length})</Title>
                    {attachmentFiles.map(file => (
                      <Card key={file.id} size="small" style={{ marginBottom: 8 }}>
                        <Row align="middle">
                          <Col flex="auto">
                            <Space>
                              <FileOutlined style={{ color: file.hasPdf ? '#52c41a' : '#1890ff' }} />
                              <div>
                                <div style={{ fontWeight: 500 }}>{file.name}</div>
                                <div style={{ fontSize: '12px', color: '#666' }}>
                                  {(file.size / 1024 / 1024).toFixed(2)} MB
                                  {file.hasPdf && file.pdfStatus === 'completed' && (
                                    <span style={{ color: '#52c41a', marginLeft: 8 }}>
                                      📄 PDF可预览
                                    </span>
                                  )}
                                  {file.pdfStatus === 'processing' && (
                                    <span style={{ color: '#1890ff', marginLeft: 8 }}>
                                      🔄 PDF生成中
                                    </span>
                                  )}
                                  {file.pdfStatus === 'placeholder' && (
                                    <span style={{ color: '#faad14', marginLeft: 8 }}>
                                      📄 PDF占位符
                                    </span>
                                  )}
                                  {file.pdfStatus === 'failed' && (
                                    <span style={{ color: '#ff4d4f', marginLeft: 8 }}>
                                      ❌ PDF转换失败
                                    </span>
                                  )}
                                </div>
                              </div>
                            </Space>
                          </Col>
                          <Col>
                            <Space>
                              {file.hasPdf && file.pdfStatus === 'completed' && (
                                <Button 
                                  type="link" 
                                  size="small"
                                  onClick={() => window.open(file.pdfUrl, '_blank')}
                                >
                                  PDF预览
                                </Button>
                              )}
                              {file.pdfStatus === 'placeholder' && (
                                <Button 
                                  type="link" 
                                  size="small"
                                  onClick={() => window.open(file.pdfUrl, '_blank')}
                                >
                                  查看占位符
                                </Button>
                              )}
                              <Button 
                                type="link" 
                                size="small"
                                onClick={() => window.open(file.url, '_blank')}
                              >
                                查看原文件
                              </Button>
                              <Button 
                                type="link" 
                                size="small" 
                                danger
                                icon={<DeleteOutlined />}
                                onClick={() => handleDeleteAttachmentFile(file.id)}
                              >
                                删除
                              </Button>
                            </Space>
                          </Col>
                        </Row>
                      </Card>
                    ))}
                  </div>
                )}
              </div>
            </TabPane>

            <TabPane 
              tab={
                <span>
                  <FileTextOutlined />
                  文档上传
                </span>
              } 
              key="upload"
            >
              <Alert
                message="文档上传转换模式"
                description="支持上传Word、PPT、PDF等文档。Word、PPT会自动转换为PDF格式便于预览；PDF文档可直接预览；其他文档会转换为HTML格式并添加到作品内容中。"
                type="success"
                showIcon
                style={{ marginBottom: 16 }}
              />

              {/* PDF转换进度条 */}
              <ConversionProgress progressData={conversionProgress} />

              <div className="document-upload-area">
                <Upload.Dragger
                  customRequest={handleDocumentUpload}
                  showUploadList={false}
                  accept=".pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.txt"
                  multiple
                  className="document-uploader"
                >
                  <p className="ant-upload-drag-icon">
                    <CloudUploadOutlined style={{ fontSize: 48, color: '#1890ff' }} />
                  </p>
                  <p className="ant-upload-text">点击或拖拽文档到此区域上传</p>
                  <p className="ant-upload-hint">
                    支持 Word (.doc, .docx)、PDF (.pdf)、PowerPoint (.ppt, .pptx)、Excel (.xls, .xlsx)、文本 (.txt)
                  </p>
                  <p className="ant-upload-hint">
                    Word、PPT文档会转换为PDF格式；PDF文档可直接预览；其他文档转换为HTML格式并添加到内容中
                  </p>
                </Upload.Dragger>

                {uploadedDocuments.length > 0 && (
                  <div className="uploaded-documents">
                    <Title level={4}>已上传文档</Title>
                    {uploadedDocuments.map((doc, index) => (
                      <Card key={index} size="small" style={{ marginBottom: 8 }}>
                        <Row align="middle">
                          <Col flex="auto">
                            <Space>
                              <FileOutlined style={{ color: doc.converted || doc.hasPdf ? '#52c41a' : '#faad14' }} />
                              <span>{doc.name}</span>
                              {doc.isPdf && (
                                <span style={{ color: '#1890ff', fontSize: '12px' }}>📄 PDF文档</span>
                              )}
                              {doc.isWordOrPpt && doc.hasPdf && doc.pdfStatus === 'completed' && (
                                <span style={{ color: '#52c41a', fontSize: '12px' }}>📄 PDF转换完成</span>
                              )}
                              {doc.isWordOrPpt && doc.pdfStatus === 'processing' && (
                                <span style={{ color: '#1890ff', fontSize: '12px' }}>🔄 PDF转换中</span>
                              )}
                              {doc.isWordOrPpt && doc.pdfStatus === 'placeholder' && (
                                <span style={{ color: '#faad14', fontSize: '12px' }}>📄 PDF占位符</span>
                              )}
                              {doc.isWordOrPpt && doc.pdfStatus === 'failed' && (
                                <span style={{ color: '#ff4d4f', fontSize: '12px' }}>❌ PDF转换失败</span>
                              )}
                              {!doc.isWordOrPpt && !doc.isPdf && doc.converted && (
                                <span style={{ color: '#52c41a', fontSize: '12px' }}>✓ HTML转换</span>
                              )}
                              {doc.hasPdf && doc.pdfStatus === 'completed' && !doc.isWordOrPpt && !doc.isPdf && (
                                <span style={{ color: '#1890ff', fontSize: '12px' }}>📄 PDF可用</span>
                              )}
                              {!doc.converted && !doc.hasPdf && (
                                <span style={{ color: '#faad14', fontSize: '12px' }}>⚠ 转换失败</span>
                              )}
                            </Space>
                          </Col>
                          <Col>
                            <Space>
                              {doc.hasPdf && (
                                <Button 
                                  type="link" 
                                  size="small"
                                  onClick={() => window.open(doc.pdfUrl, '_blank')}
                                >
                                  PDF预览
                                </Button>
                              )}
                              <Button 
                                type="link" 
                                size="small"
                                onClick={() => window.open(doc.url, '_blank')}
                              >
                                {doc.isPdf ? '查看PDF' : '查看原文件'}
                              </Button>
                            </Space>
                          </Col>
                        </Row>
                      </Card>
                    ))}
                  </div>
                )}
              </div>
            </TabPane>
          </Tabs>

          <Divider />

          {/* 操作按钮区域 */}
          <div className="action-buttons">
            <Row gutter={[16, 16]}>
              <Col xs={24} sm={12} md={6}>
                <Upload
                  customRequest={handleCoverUpload}
                  showUploadList={false}
                  accept="image/*"
                >
                  <Button 
                    icon={<PictureOutlined />} 
                    block
                    type={coverImage ? "default" : "dashed"}
                  >
                    {coverImage ? '更换封面' : '上传封面'}
                  </Button>
                </Upload>
              </Col>

              <Col xs={24} sm={12} md={6}>
                <Button 
                  icon={<SaveOutlined />} 
                  onClick={handleSaveDraft}
                  loading={saving}
                  block
                >
                  保存草稿
                </Button>
              </Col>

              <Col xs={24} sm={12} md={6}>
                <Button 
                  icon={<EyeOutlined />} 
                  onClick={handlePreview}
                  block
                >
                  预览
                </Button>
              </Col>

              <Col xs={24} sm={12} md={6}>
                <Button 
                  type="primary"
                  icon={<SendOutlined />} 
                  onClick={handlePublish}
                  loading={publishing}
                  block
                >
                  发布作品
                </Button>
              </Col>
            </Row>
          </div>

          {/* 封面预览 */}
          {coverImage && (
            <div className="cover-preview">
              <Text strong style={{ fontSize: '14px' }}>封面预览:</Text>
              <div style={{ marginTop: 12 }}>
                <img 
                  src={coverImage} 
                  alt="封面预览" 
                  className="cover-image"
                />
                <div style={{ marginTop: 12 }}>
                  <Button 
                    type="link" 
                    size="small" 
                    danger
                    onClick={() => setCoverImage(null)}
                  >
                    删除封面
                  </Button>
                </div>
              </div>
            </div>
          )}

          {/* 附件列表 */}
          {attachments.length > 0 && (
            <div className="attachments-section">
              <Title level={4} className="section-title">
                <FileOutlined style={{ marginRight: 8 }} />
                附件列表 ({attachments.length})
              </Title>
              
              {attachments.map(attachment => (
                <Card 
                  key={attachment.id} 
                  size="small" 
                  className="attachment-item"
                >
                  <Row align="middle" justify="space-between">
                    <Col flex="auto">
                      <Space>
                        <FileOutlined style={{ fontSize: '16px', color: '#1890ff' }} />
                        <div className="attachment-info">
                          <div className="attachment-name">{attachment.name}</div>
                          <div className="attachment-size">
                            {(attachment.size / 1024 / 1024).toFixed(2)} MB
                          </div>
                        </div>
                      </Space>
                    </Col>
                    <Col>
                      <Space className="attachment-actions">
                        {attachment.hasPdf && (
                          <Button 
                            type="link" 
                            size="small"
                            onClick={() => window.open(attachment.pdfUrl, '_blank')}
                          >
                            PDF预览
                          </Button>
                        )}
                        <Button 
                          type="link" 
                          size="small"
                          onClick={() => window.open(attachment.url, '_blank')}
                        >
                          下载
                        </Button>
                        <Button 
                          type="link" 
                          size="small" 
                          danger
                          icon={<DeleteOutlined />}
                          onClick={() => handleDeleteAttachment(attachment.id)}
                        >
                          删除
                        </Button>
                      </Space>
                    </Col>
                  </Row>
                </Card>
              ))}
            </div>
          )}
        </Form>
      </Card>

      {/* 预览模态框 */}
      <Modal
        title="作品预览"
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        footer={null}
        width="90%"
        style={{ top: 20 }}
        className="preview-modal"
      >
        <div 
          className="preview-content"
          dangerouslySetInnerHTML={{ __html: previewContent }}
        />
      </Modal>
    </div>
  );
};

export default Works;